<script setup lang="ts">
import { computed, ref } from 'vue';
import { NUpload, useMessage } from 'naive-ui';
import type { UploadFileInfo } from 'naive-ui';
import { fetchResetPassword, fetchUpdateUserInfo, fetchUserInfo } from '@/service/api';
import { useAuthStore } from '@/store/modules/auth';
import AvatarFrameSelector from './avatar-frame-selector.vue';

defineOptions({
  name: 'UserInfoCard'
});

const authStore = useAuthStore();
const userInfo = ref<Api.User.UserInfo | null>(null);
const loading = ref(false);
const showEditModal = ref(false);
const editForm = ref({
  username: '',
  email: '',
  gender: '',
  avatar: ''
});
const saveLoading = ref(false);
const resetPwdModal = ref(false);
const resetPwdLoading = ref(false);
const newPassword = ref('');
const message = useMessage();

// 格式化余额显示
const formattedBalance = computed(() => {
  if (!userInfo.value || userInfo.value.accountBalance === undefined || userInfo.value.accountBalance === null) {
    return '0.00';
  }

  // 处理不同类型的余额值
  let balance: number;
  if (typeof userInfo.value.accountBalance === 'string') {
    balance = Number.parseFloat(userInfo.value.accountBalance);
  } else {
    balance = userInfo.value.accountBalance;
  }

  // 检查是否为有效数字
  if (Number.isNaN(balance)) {
    return '0.00';
  }

  return balance.toFixed(2);
});

// 获取用户信息
const loadUserInfo = async () => {
  if (!authStore.userInfo.userId) return;

  loading.value = true;
  try {
    const { data } = await fetchUserInfo(authStore.userInfo.userId);
    if (data) {
      console.log('=== 用户信息调试 ===');
      console.log('原始数据:', data);
      console.log('accountBalance:', data.accountBalance);
      console.log('accountBalance类型:', typeof data.accountBalance);
      console.log('accountBalance值:', data.accountBalance);
      userInfo.value = data;
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  } finally {
    loading.value = false;
  }
};

// 打开编辑模态框
const openEditModal = () => {
  if (userInfo.value) {
    editForm.value = {
      username: userInfo.value.username,
      email: userInfo.value.email,
      gender: userInfo.value.gender,
      avatar: userInfo.value.avatar
    };
    showEditModal.value = true;
  }
};

// 性别字段编码处理，防止前端传参乱码
function encodeGender(gender: string) {
  if (gender === '男' || gender === '女') {
    return decodeURIComponent(encodeURIComponent(gender));
  }
  return gender;
}

// 性别展示映射
const genderDisplay = (gender: string) => {
  if (gender === 'Male') return '男';
  if (gender === 'Female') return '女';
  return '未设置性别';
};

// 保存用户信息
const saveUserInfo = async () => {
  if (!userInfo.value || saveLoading.value) return;
  saveLoading.value = true;
  try {
    await fetchUpdateUserInfo({
      id: userInfo.value.id,
      ...editForm.value,
      gender: encodeGender(editForm.value.gender)
    });
    await loadUserInfo();
    showEditModal.value = false;
    window.$message?.success('用户信息更新成功');
  } catch (error) {
    console.error('更新用户信息失败:', error);
    window.$message?.error('用户信息更新失败');
  } finally {
    saveLoading.value = false;
  }
};

const handleAvatarUpload = (data: { file: UploadFileInfo }) => {
  const rawFile = data.file.file;
  if (!rawFile) return;
  const reader = new FileReader();
  reader.onload = event => {
    const result = event.target?.result;
    if (typeof result === 'string') {
      editForm.value.avatar = result;
    }
  };
  reader.readAsDataURL(rawFile);
};

const handleResetPassword = async () => {
  if (!userInfo.value || !newPassword.value) return;
  resetPwdLoading.value = true;
  try {
    await fetchResetPassword(userInfo.value.phoneNumber, userInfo.value.username, newPassword.value);
    message.success('密码重置成功');
    resetPwdModal.value = false;
    newPassword.value = '';
  } catch {
    message.error('密码重置失败');
  } finally {
    resetPwdLoading.value = false;
  }
};

// 头像框相关
const avatarFrameKey = ref(localStorage.getItem('avatarFrameKey') || 'rainbow');
const showFrameSelector = ref(false);
function handleSelectFrame(key: string) {
  avatarFrameKey.value = key;
  localStorage.setItem('avatarFrameKey', key);
  showFrameSelector.value = false;
}

// 初始化
loadUserInfo();

// 暴露 loadUserInfo 方法给父组件调用（如充值后自动刷新余额）
defineExpose({ loadUserInfo });
</script>

<template>
  <NCard :bordered="false" class="card-wrapper">
    <template #header>
      <div class="flex items-center justify-between">
        <div class="header-icon">
          <SvgIcon icon="mdi:account-circle" />
        </div>
        <span class="text-20px text-gray-800 font-bold">个人信息</span>
        <NButton type="primary" size="medium" class="edit-btn" @click="openEditModal">
          <template #icon>
            <SvgIcon icon="mdi:pencil" />
          </template>
          编辑资料
        </NButton>
      </div>
    </template>
    <NSpin :show="loading">
      <div v-if="userInfo" class="user-info-content">
        <!-- 用户基本信息 -->
        <div class="user-basic-info">
          <div class="avatar-container">
            <div class="avatar-frame-wrapper">
              <div class="avatar-frame" :class="[avatarFrameKey]">
                <img
                  :src="userInfo.avatar || '/src/assets/imgs/soybean.jpg'"
                  :alt="userInfo.username || '用户头像'"
                  class="avatar-image"
                />
                <!-- 魔法棒按钮 -->
                <div class="avatar-frame-btn" @click.stop="showFrameSelector = true">
                  <SvgIcon icon="mdi:magic-wand" />
                </div>
              </div>
              <div class="avatar-status"></div>
            </div>
          </div>
          <div class="user-details">
            <div class="username">
              <SvgIcon icon="mdi:account" class="username-icon" />
              {{ userInfo.username || '未知用户' }}
            </div>
            <div class="user-meta">
              <div class="meta-item">
                <SvgIcon icon="mdi:email" class="meta-icon" />
                {{ userInfo.email || '未设置邮箱' }}
              </div>
              <div class="meta-item">
                <SvgIcon icon="mdi:gender-male-female" class="meta-icon" />
                {{ genderDisplay(userInfo.gender) }}
              </div>
            </div>
          </div>
        </div>
        <!-- 头像框选择器弹窗 -->
        <NModal
          v-model:show="showFrameSelector"
          preset="card"
          style="width: 440px; background: transparent; box-shadow: none"
        >
          <AvatarFrameSelector
            :avatar="userInfo.avatar || '/src/assets/imgs/soybean.jpg'"
            :selected-key="avatarFrameKey"
            @select="handleSelectFrame"
            @close="showFrameSelector = false"
          />
        </NModal>
        <!-- 账户数据 -->
        <div class="account-stats">
          <div class="stat-card balance-card">
            <div class="stat-icon">
              <SvgIcon icon="mdi:cash" />
            </div>
            <div class="stat-content">
              <div class="stat-value">¥{{ formattedBalance }}</div>
              <div class="stat-label">账户余额</div>
            </div>
            <div class="stat-decoration"></div>
          </div>
          <div class="stat-card points-card">
            <div class="stat-icon">
              <SvgIcon icon="mdi:star" />
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ userInfo.accountPoints || 0 }}</div>
              <div class="stat-label">积分</div>
            </div>
            <div class="stat-decoration"></div>
          </div>
        </div>
      </div>
    </NSpin>

    <!-- 编辑模态框 -->
    <Transition name="modal-zoom-fade">
      <NModal
        v-model:show="showEditModal"
        preset="card"
        class="edit-modal"
        :style="{ width: '420px', padding: 0, background: 'transparent' }"
      >
        <div class="edit-modal-inner">
          <div class="edit-modal-bar"></div>
          <div class="edit-modal-title">编辑个人信息</div>
          <NForm :model="editForm" label-placement="left" label-width="80" class="edit-modal-form">
            <NFormItem label="用户名">
              <NInput v-model:value="editForm.username" placeholder="请输入用户名" class="edit-input" />
            </NFormItem>
            <NFormItem label="邮箱">
              <NInput v-model:value="editForm.email" placeholder="请输入邮箱" class="edit-input" />
            </NFormItem>
            <NFormItem label="性别">
              <NSelect
                v-model:value="editForm.gender"
                :options="[
                  { label: '男', value: 'Male' },
                  { label: '女', value: 'Female' }
                ]"
                placeholder="请选择性别"
                class="edit-input"
              />
            </NFormItem>
            <NFormItem label="头像">
              <div class="avatar-upload-area">
                <div class="avatar-upload-box">
                  <div class="avatar-gradient-border">
                    <img :src="editForm.avatar || '/src/assets/imgs/soybean.jpg'" class="edit-avatar" />
                  </div>
                  <div class="avatar-upload-btn-wrap">
                    <NUpload :show-file-list="false" :max="1" accept="image/*" @change="handleAvatarUpload">
                      <NButton size="small" class="upload-btn">上传头像</NButton>
                    </NUpload>
                  </div>
                </div>
              </div>
            </NFormItem>
          </NForm>
          <div class="edit-modal-footer">
            <NButton tertiary class="reset-btn" @click="resetPwdModal = true">
              <template #icon><SvgIcon icon="mdi:lock-reset" /></template>
              重置密码
            </NButton>
            <div class="footer-btns">
              <NButton class="cancel-btn" @click="showEditModal = false">取消</NButton>
              <NButton
                type="primary"
                class="save-btn"
                :loading="saveLoading"
                :disabled="saveLoading"
                @click="saveUserInfo"
              >
                保存
              </NButton>
            </div>
          </div>
        </div>
      </NModal>
    </Transition>

    <NModal v-model:show="resetPwdModal" preset="dialog" title="重置密码">
      <NInput v-model:value="newPassword" type="password" placeholder="请输入新密码" />
      <template #footer>
        <NButton @click="resetPwdModal = false">取消</NButton>
        <NButton type="primary" :loading="resetPwdLoading" @click="handleResetPassword">确定</NButton>
      </template>
    </NModal>
  </NCard>
</template>

<style scoped>
.card-wrapper {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.95), rgba(255, 255, 255, 0.85));
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
}

.card-wrapper:hover {
  transform: translateY(-4px);
  box-shadow: 0 16px 48px rgba(0, 0, 0, 0.12);
}

.card-wrapper::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #667eea, #764ba2, #f093fb, #f5576c);
  background-size: 400% 100%;
  animation: gradient-shift 3s ease-in-out infinite;
}

@keyframes gradient-shift {
  0%,
  100% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
}

.header-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  font-size: 20px;
}

.edit-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 12px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.edit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}

.user-info-content {
  padding: 8px 0;
}

.user-basic-info {
  display: flex;
  align-items: center;
  gap: 24px;
  margin-bottom: 32px;
  padding: 24px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 0.6));
  border-radius: 20px;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.avatar-container {
  position: relative;
}

.avatar-frame-wrapper {
  position: relative;
  width: 104px;
  height: 104px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.avatar-frame {
  width: 104px;
  height: 104px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  transition: box-shadow 0.3s;
  background: #fff;
}
.avatar-image {
  width: 92px;
  height: 92px;
  border-radius: 50%;
  object-fit: cover;
  background: #f5f7fa;
  z-index: 1;
  box-shadow: 0 2px 8px #667eea22;
}
.avatar-status {
  position: absolute;
  bottom: 4px;
  right: 4px;
  width: 24px;
  height: 24px;
  background: linear-gradient(135deg, #48bb78, #38a169);
  border: 3px solid white;
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.avatar-glow {
  position: absolute;
  inset: -2px;
  background: linear-gradient(45deg, #667eea, #764ba2, #f093fb, #f5576c);
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: -1;
}

.avatar-wrapper:hover .avatar-glow {
  opacity: 0.3;
}

.user-details {
  flex: 1;
}

.username {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 700;
  color: #2d3748;
  margin-bottom: 12px;
}

.username-icon {
  margin-right: 12px;
  color: #667eea;
  font-size: 24px;
}

.user-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #718096;
  transition: all 0.3s ease;
}

.meta-item:hover {
  color: #4a5568;
  transform: translateX(4px);
}

.meta-icon {
  margin-right: 8px;
  color: #667eea;
  font-size: 16px;
}

.account-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.stat-card {
  position: relative;
  display: flex;
  align-items: center;
  padding: 24px;
  border-radius: 20px;
  color: white;
  overflow: hidden;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
}

.balance-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.points-card {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  margin-right: 16px;
  font-size: 24px;
  backdrop-filter: blur(10px);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 4px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
  font-weight: 500;
}

.stat-decoration {
  position: absolute;
  top: -20px;
  right: -20px;
  width: 80px;
  height: 80px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  backdrop-filter: blur(10px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-basic-info {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }

  .avatar-wrapper {
    width: 80px;
    height: 80px;
  }

  .username {
    font-size: 20px;
    justify-content: center;
  }

  .account-stats {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .stat-card {
    padding: 20px;
  }

  .stat-value {
    font-size: 24px;
  }
}

.edit-modal {
  --n-border-radius: 20px !important;
  --n-box-shadow: 0 12px 48px rgba(102, 126, 234, 0.18);
  --n-padding: 0 !important;
  background: transparent !important;
}
.edit-modal-inner {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.98) 60%, rgba(245, 247, 250, 0.92) 100%);
  backdrop-filter: blur(18px);
  border-radius: 20px;
  box-shadow: 0 12px 48px rgba(102, 126, 234, 0.18);
  padding: 0 0 22px 0;
  overflow: hidden;
  position: relative;
}
.edit-modal-bar {
  width: 100%;
  height: 6px;
  background: linear-gradient(90deg, #667eea, #764ba2, #f093fb, #f5576c);
  border-radius: 20px 20px 0 0;
  box-shadow: 0 0 12px 2px #f093fb55;
  margin-bottom: 0px;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
}
.edit-modal-title {
  font-size: 26px;
  font-weight: 800;
  color: #222;
  padding: 28px 32px 10px 32px;
  letter-spacing: 1px;
  text-align: left;
  background: none;
}
.edit-modal-form {
  padding: 0 32px 0 32px;
  margin-top: 8px;
}
.edit-modal-form :deep(.n-form-item) {
  margin-bottom: 22px;
  align-items: flex-start;
}
.edit-modal-form :deep(.n-form-item-label) {
  font-weight: 700;
  font-size: 16px;
  color: #222;
  text-align: left;
  padding-right: 12px;
  line-height: 40px;
}
.edit-input :deep(.n-input),
.edit-input :deep(.n-base-selection-label) {
  border-radius: 12px !important;
  font-size: 16px;
  padding-left: 18px !important;
  padding-right: 18px !important;
  height: 40px !important;
  line-height: 40px !important;
  transition: box-shadow 0.2s;
}
.edit-input :deep(.n-input:focus),
.edit-input :deep(.n-base-selection-label:focus) {
  box-shadow: 0 0 0 2px #667eea55;
}
.avatar-upload-area {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-left: 92px;
}
.avatar-upload-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}
.avatar-gradient-border {
  padding: 3px;
  border-radius: 50%;
  background: conic-gradient(from 0deg, #667eea, #764ba2, #f093fb, #f5576c, #667eea);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: box-shadow 0.3s;
  box-shadow: 0 0 0 0 #fff0;
}
.avatar-gradient-border:hover {
  box-shadow: 0 0 16px 4px #764ba2aa;
}
.edit-avatar {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  object-fit: cover;
  box-shadow: 0 2px 8px #667eea22;
  transition:
    box-shadow 0.3s,
    transform 0.3s;
}
.edit-avatar:hover {
  box-shadow: 0 4px 24px #764ba255;
  transform: scale(1.08);
}
.avatar-upload-btn-wrap {
  margin-top: 6px;
}
.upload-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border-radius: 12px;
  font-weight: 600;
  transition: all 0.25s cubic-bezier(0.4, 2, 0.6, 1);
  border: none;
  box-shadow: 0 2px 8px #667eea22;
  padding: 0 18px;
  height: 36px;
  font-size: 15px;
}
.upload-btn:hover {
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
  transform: scale(1.08) translateY(-2px);
  box-shadow: 0 4px 16px #764ba255;
}
.edit-modal-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 22px 32px 0 32px;
  gap: 0;
}
.reset-btn {
  color: #667eea;
  font-weight: 500;
  background: none;
  border: none;
  transition: color 0.2s;
  font-size: 15px;
  margin-right: auto;
  height: 40px;
  display: flex;
  align-items: center;
}
.reset-btn:hover {
  color: #764ba2;
}
.footer-btns {
  display: flex;
  gap: 22px;
}
.cancel-btn,
.save-btn {
  height: 40px;
  min-width: 80px;
  font-size: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.cancel-btn {
  background: #f5f7fa;
  color: #718096;
  border-radius: 12px;
  border: none;
  font-weight: 500;
  transition: all 0.2s;
}
.cancel-btn:hover {
  background: #e0e7ef;
  color: #2d3748;
}
.save-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border-radius: 12px;
  font-weight: 700;
  border: none;
  transition: all 0.2s cubic-bezier(0.4, 2, 0.6, 1);
  box-shadow: 0 2px 8px #667eea22;
}
.save-btn:hover {
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
  transform: scale(1.08) translateY(-2px);
  box-shadow: 0 4px 16px #764ba255;
}
/* 弹窗动画 */
.modal-zoom-fade-enter-active,
.modal-zoom-fade-leave-active {
  transition: all 0.35s cubic-bezier(0.4, 2, 0.6, 1);
}
.modal-zoom-fade-enter-from,
.modal-zoom-fade-leave-to {
  opacity: 0;
  transform: scale(0.85);
}
.avatar-frame {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  transition: box-shadow 0.3s;
}
.avatar-frame.rainbow {
  border: 4px solid;
  border-image: linear-gradient(135deg, #ff6b6b, #fbc531, #4cd137, #00a8ff, #9c88ff, #e17055) 1;
}
.avatar-frame.gold {
  border: 4px solid #ffd700;
  box-shadow: 0 0 12px 2px #ffd70088;
}
.avatar-frame.neon {
  border: 4px solid #00c3ff;
  box-shadow: 0 0 16px 2px #00c3ffcc;
}
.avatar-frame.dream {
  border: 4px solid;
  border-image: linear-gradient(135deg, #f093fb, #f5576c, #a18cd1, #fbc2eb) 1;
  box-shadow: 0 0 12px 2px #f093fb55;
}
.avatar-frame.white {
  border: 4px solid #fff;
  box-shadow: 0 0 8px 1px #e0e7ef;
}
.avatar-frame.pixel {
  border: 4px dashed #333;
  background: repeating-linear-gradient(45deg, #fff, #fff 4px, #eee 4px, #eee 8px);
}
.avatar-frame-btn {
  position: absolute;
  right: -8px;
  bottom: -8px;
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 18px;
  box-shadow: 0 2px 8px #667eea33;
  cursor: pointer;
  border: 2px solid #fff;
  transition:
    box-shadow 0.2s,
    transform 0.2s;
  z-index: 2;
}
.avatar-frame-btn:hover {
  box-shadow: 0 4px 16px #764ba255;
  transform: scale(1.08);
}
</style>
